import sys
import numpy as np
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget, QPushButton
from PyQt5.QtCore import QTimer
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class BubbleSortAnimation(QWidget):
    def __init__(self):
        super().__init__()

        self.numbers = [5, 3, 8, 4, 2]
        self.i = 0
        self.j = 0
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_sort)

        self.initUI()

    def initUI(self):
        self.setWindowTitle('Bubble Sort Animation')
        self.setGeometry(100, 100, 800, 600)

        self.layout = QVBoxLayout()

        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.layout.addWidget(self.canvas)

        self.start_button = QPushButton('Start Sort', self)
        self.start_button.clicked.connect(self.start_sort)
        self.layout.addWidget(self.start_button)

        self.setLayout(self.layout)
        self.plot_bars()

    def start_sort(self):
        self.i = 0
        self.j = 0
        self.numbers = [5, 3, 8, 4, 2]  # 重置排序数组
        self.timer.start(500)  # 每500毫秒更新一次

    def update_sort(self):
        if self.i < len(self.numbers):
            if self.j < len(self.numbers) - self.i - 1:
                if self.numbers[self.j] > self.numbers[self.j + 1]:
                    self.numbers[self.j], self.numbers[self.j + 1] = self.numbers[self.j + 1], self.numbers[self.j]
                self.j += 1
            else:
                self.j = 0
                self.i += 1
            self.plot_bars()
        else:
            self.timer.stop()

    def plot_bars(self):
        self.figure.clear()
        ax = self.figure.add_subplot(111)
        bar_colors = ['b'] * len(self.numbers)
        if self.i < len(self.numbers) and self.j < len(self.numbers) - self.i - 1:
            bar_colors[self.j] = 'r'
            bar_colors[self.j + 1] = 'r'
        ax.bar(range(len(self.numbers)), self.numbers, color=bar_colors)
        self.canvas.draw()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = BubbleSortAnimation()
    ex.show()
    sys.exit(app.exec_())
